import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useMemo,
  useState,
} from "react";
import iqcService from "@/api/services/qms/iqcService";
import { TableToolbar } from "@/components/grid/TableToolbar";
import { Button, Input, InputNumber } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import { toast } from "sonner";
import type { QmsIqcDetail } from "./entity";

import MultiQcIndexSelect from "@/pages/components/selector/MultiQcIndexSelect";
import { QmsIndex } from "../index/entity";
import QmsIqcRecordPage from "./iqcRecord";


interface QmsIqcDetailProps {
  parentId?: React.Key;
  isView?: boolean;
  isCheck?: boolean;
}

export interface QmsIqcDetailHandles {
  getAddList: () => QmsIqcDetail[];
  getUpdateList: () => QmsIqcDetail[];
  getDeleteIds: () => React.Key[];
}

const QmsIqcDetailPage = forwardRef<QmsIqcDetailHandles, QmsIqcDetailProps>(
  ({ parentId, isView = false, isCheck = false }, ref) => {
    const [loading, setLoading] = useState(false);
    const [list, setList] = useState<QmsIqcDetail[]>([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [editedRowKey, setEditedRowKey] = useState<React.Key>();
    // 添加一个状态来跟踪临时ID
    const [tempIds, setTempIds] = useState<React.Key[]>([]);
    const [addList, setAddList] = useState<QmsIqcDetail[]>([]);
    const [updateList, setUpdateList] = useState<QmsIqcDetail[]>([]);
    const [deleteIds, setDeleteIds] = useState<React.Key[]>([]);
    const [indexSelectVisiable, setIndexSelectVisiable] = useState(false);
    const [recordVisible, setRecordVisible] = useState(false);

    useImperativeHandle(
      ref,
      () => ({
        getAddList: () => addList,
        getUpdateList: () => updateList,
        getDeleteIds: () => deleteIds,
      }),
      [addList, updateList, deleteIds]
    );

    useEffect(() => {
      const newAddList = list.filter(
        (item) => item.id && tempIds.includes(item.id)
      );
      setAddList(newAddList);
      const updateList = list.filter(
        (item) => item.id && !tempIds.includes(item.id)
      );
      setUpdateList(updateList);
    }, [list]);

    const [tableSize, setTableSize] = useState<"large" | "middle" | "small">(
      "middle"
    );

    //动态设置表格高度
    const [tableScrollY, setTableScrollY] = useState(0);
    const PAGE_OFFSET_HEIGHT = 403;
    const updateTableHeight = () => {
      const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
      setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
    };

    // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
    useEffect(() => {
      updateTableHeight(); // 初始化
      window.addEventListener("resize", updateTableHeight);
      return () => window.removeEventListener("resize", updateTableHeight);
    }, []);

    //表格列定义
    const columns: ColumnsType<QmsIqcDetail> = [
      {
        title: "检测项编码",
        width: 120,
        key: "indexCode",
        dataIndex: "indexCode"
      },
      {
        title: "检测项名称",
        width: 120,
        key: "indexName",
        dataIndex: "indexName"
      },
      {
        title: "检测项类型",
        width: 120,
        key: "indexType",
        dataIndex: "indexType"
      },
      {
        title: "检测工具",
        width: 120,
        key: "qcTool",
        dataIndex: "qcTool"
      },
      {
        title: "检测要求",
        width: 120,
        key: "checkMethod",
        dataIndex: "checkMethod",
        render: (text, record) => (
          <> 
            {isView ? text : (
              <Input
                value={text}
                onChange={(e) =>
                  handleFieldChange(record.id, "checkMethod", e.target.value)
                }
                allowClear
              />
            )}
          </>
        ),
      },
      {
        title: "标准值",
        width: 80,
        key: "standerVal",
        dataIndex: "standerVal",
        render: (text, record) => (
          <>
            {isView ? text : (
              <Input
                value={text}
                onChange={(e) =>
                  handleFieldChange(record.id, "standerVal", e.target.value)
                }
                allowClear
              />
            )}
          </>
        ),
      },
      {
        title: "单位",
        width: 80,
        key: "unitOfMeasure",
        dataIndex: "unitOfMeasure",
        render: (text, record) => (
          <>
            {isView ? text : (
              <Input
                value={text}
                onChange={(e) =>
                  handleFieldChange(record.id, "unitOfMeasure", e.target.value)
                }
                allowClear
              />
            )}
          </>
        ),
      },
      {
        title: "误差上限",
        width: 60,
        key: "thresholdMax",
        dataIndex: "thresholdMax",
        render: (text, record) => (
          <>
            {isView ? text : (
              <Input
                value={text}
                onChange={(e) =>
                  handleFieldChange(record.id, "thresholdMax", e.target.value)
                }
                allowClear
              />
            )}
          </>
        ),
      },
      {
        title: "误差下限",
        width: 60,
        key: "thresholdMin",
        dataIndex: "thresholdMin",
        render: (text, record) => (
          <>
            {isView ? text : (
              <Input
                value={text}
                onChange={(e) =>
                  handleFieldChange(record.id, "thresholdMin", e.target.value)
                }
                allowClear
              />
            )}
          </>
        ),
      },
      {
        title: "致命缺陷数量",
        width: 60,
        key: "crQty",
        dataIndex: "crQty",
        render: (text, record) => (
          <>
            {isView ? text : (
              <InputNumber
                value={text}
                onChange={(value) => handleFieldChange(record.id, "crQty", value)}
                style={{ width: "100%" }}
              />
            )}
          </>
        ),
      },
      {
        title: "严重缺陷数量",
        width: 60,
        key: "majQty",
        dataIndex: "majQty",
        render: (text, record) => (
          <>
            {isView ? text : (
              <InputNumber
                value={text}
                onChange={(value) => handleFieldChange(record.id, "majQty", value)}
                style={{ width: "100%" }}
              />
            )}
          </>
        ),
      },
      {
        title: "轻微缺陷数量",
        width: 60,
        key: "minQty",
        dataIndex: "minQty",
        render: (text, record) => (
          <>
            {isView ? text : (
              <InputNumber
                value={text}
                onChange={(value) => handleFieldChange(record.id, "minQty", value)}
                style={{ width: "100%" }}
              />
            )}
          </>
        ),
      },
      {
        title: "备注",
        width: 100,
        key: "remark",
        dataIndex: "remark",
        render: (text, record) => (
          <>
            {isView ? text : (
              <Input
                value={text}
                onChange={(e) =>
                  handleFieldChange(record.id, "remark", e.target.value)
                }
              />
            )}
          </>
        ),
      },
      {
        title: "操作",
        fixed: "right",
        key: "operation",
        align: "center",
        width: 100,
        render: (_, record) => (
          <>
            {isCheck ? null : (
              <Button type="link" onClick={() => handleAddRecord(record)}>
                缺陷记录
              </Button>
            )}
          </>
        ),
      },
    ];

    const [selectedValues, setSelectedValues] = useState<string[]>(() =>
      columns
        .filter((col) => col.key !== "operation")
        .map((col) => (col.key ? String(col.key) : ""))
    );

    // 处理字段变更
    const handleFieldChange = (id: string, field: string, value: any) => {
      let inputValue: any = null;
      // 如果是checkbox的值，将布尔值转换为数字值（true为1，false为0）
      if (typeof value === "boolean") {
        inputValue = value ? 1 : 0;
      } else if (value instanceof Date) {
        // 处理日期格式
        inputValue = dayjs(value).format("YYYY-MM-DD");
      } else {
        inputValue = value;
      }

      setList((prevData) =>
        prevData.map((item) =>
          item.id === id ? { ...item, [field]: inputValue } : item
        )
      );
    };

    // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
    const filteredColumns = useMemo(() => {
      return [
        ...columns.filter(
          (col) =>
            selectedValues.includes(String(col.key)) || col.key === "operation"
        ),
      ].sort((a, b) => {
        const originalIndex = columns.findIndex((c) => c.key === a.key);
        const targetIndex = columns.findIndex((c) => c.key === b.key);
        return originalIndex - targetIndex;
      });
    }, [selectedValues]);

    //加载表格数据
    const fetchList = () => {
      if (!parentId) return;

      setLoading(true);
      iqcService
        .getIqcDetails(parentId)
        .then((res) => {
          setList(res);
        })
        .catch((error) => {
          console.log(error);
          toast.error("获取数据失败！", error);
        })
        .finally(() => {
          setLoading(false);
        });
    };

    // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
    useEffect(() => {
      if (parentId) {
        fetchList();
      } else {
        // 初始化时清空状态
        setList([]);
        setSelectedRowKeys([]);
        setTempIds([]);
        setAddList([]);
        setUpdateList([]);
        setDeleteIds([]);
      }
    }, [parentId]);

    const handleAdd = () => {
      setIndexSelectVisiable(true);
    };

    // 在删除方法中修改判断逻辑
    const handleDelete = () => {
      // 如果没有选中行，直接返回
      if (selectedRowKeys.length === 0) {
        return;
      }

      // 更新删除ID列表
      const newDeleteIds = [...deleteIds];

      // 将已有ID但不在deleteIds中的ID添加到deleteIds
      for (const key of selectedRowKeys) {
        const item = list.find((item) => item.id === key);
        if (item?.id && !tempIds.includes(item.id)) {
          // 如果不在临时ID列表中，则添加到删除列表
          if (!newDeleteIds.includes(item.id)) {
            newDeleteIds.push(item.id);
          }
        }
      }

      // 更新deleteIds状态
      setDeleteIds(newDeleteIds);

      // 从列表中移除选中的行
      setList((prevList) =>
        prevList.filter((item) => !selectedRowKeys.includes(item.id))
      );
      // 从tempIds中移除被删除的临时ID
      setTempIds((prevTempIds) =>
        prevTempIds.filter((id) => !selectedRowKeys.includes(id))
      );
      // 清空选中状态
      setSelectedRowKeys([]);
    };

    const handleAddRecord = (record: QmsIqcDetail) => {
      setEditedRowKey(record.id);
      setRecordVisible(true);
    };

    const handleSelectQcIndex = (qcIndexes: QmsIndex[]) => {
      setIndexSelectVisiable(false);

      // 先获取已存在的 materialId 列表
      const existMaterialIds = list.map((item) => item.materialId);

      // 只添加不存在于 list 中的 material
      const newQcIndexList: QmsIqcDetail[] = qcIndexes
        .filter((qcIndex) => !existMaterialIds.includes(qcIndex.indexId))
        .map((qcIndex) => ({
          id: qcIndex.id,
          iqcId: parentId,
          indexId: qcIndex.id,
          indexCode: qcIndex.indexCode,
          indexName: qcIndex.indexName,
          indexType: qcIndex.indexType,
          qcTool: qcIndex.qcTool,
        }));

      setList((prevList) => [...prevList, ...newQcIndexList]);

      // 添加到临时ID列表
      const newTempIds = newQcIndexList.map((item) => item.id);
      setTempIds((prev) => [...prev, ...newTempIds]);
    };

    const handleRecordDrawerClose = (refresh?: boolean) => {
      setRecordVisible(false);
      if (refresh) {
        fetchList();
      }
    };

    return (
      <>
        <div className="flex justify-between mb-4">
          {!isView && (
          <div className="flex gap-2">
            <Button type="primary" onClick={handleAdd}>
              新增
            </Button>
            <Button
              danger
              disabled={selectedRowKeys.length === 0}
              onClick={handleDelete}
            >
              删除
            </Button>
          </div>
          )}
          <TableToolbar
            onRefresh={() => fetchList()}
            onSizeChange={setTableSize}
            columns={columns}
            selectedValues={selectedValues}
            onColumnChange={setSelectedValues}
          />
        </div>
        <Table
          rowKey="id"
          size={tableSize}
          scroll={{ x: "max-content", y: tableScrollY }}
          loading={loading}
          pagination={false}
          columns={filteredColumns}
          dataSource={list}
          rowSelection={{
            type: "checkbox",
            selectedRowKeys: selectedRowKeys,
            onChange: (selectedKeys) => {
              setSelectedRowKeys(selectedKeys as React.Key[]);
            },
          }}
        />

        {/* 检测项选择器 */}
        <MultiQcIndexSelect
          open={indexSelectVisiable}
          onCancel={() => setIndexSelectVisiable(false)}
          onOk={(item) => handleSelectQcIndex(item)}
        />

        <QmsIqcRecordPage
          iqcId={parentId}
          detailId={editedRowKey}
          recordVisible={recordVisible}
          isView={isView}
          handleDrawerClose={handleRecordDrawerClose}
        />
      </>
    );
  }
);

export default QmsIqcDetailPage;
